package com.zfl.filter;

import com.zfl.util.RedisUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class RolePermissionFilter implements Filter {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("开始过滤");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestUrl = request.getRequestURI();
        System.out.println("requestUrl = " + requestUrl);
        if (requestUrl.contains("init")||requestUrl.contains("login")) {
            System.out.println("初始登录放行");
            filterChain.doFilter(request,response);
            return;
        }




        HttpSession session = request.getSession();

        String userId = session.getAttribute("userId").toString();
        System.out.println("userId = " + userId);
        Object id1 = redisUtil.getObjectFromByte(requestUrl);
        System.out.println("id1 = " + id1);
        int urlid  = (int) id1;
        System.out.println("urlid = " + urlid);

        Object id2 = redisUtil.getObjectFromByte(userId);
        System.out.println("id2 = " + id2);
        int roleid = (int) id2;

        System.out.println("roleid = " + roleid);
        if (urlid==roleid) {
            filterChain.doFilter(request,response);
        }else {
            // 无权限，返回403
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "无访问权限");
        }

    }
}
